package com.molichuxing.services.sdk;

import com.timevale.esign.sdk.tech.bean.PersonBean;
import com.timevale.esign.sdk.tech.bean.PosBean;
import com.timevale.esign.sdk.tech.bean.SignPDFStreamBean;
import com.timevale.esign.sdk.tech.bean.UpdatePersonBean;
import com.timevale.esign.sdk.tech.bean.result.*;
import com.timevale.esign.sdk.tech.bean.seal.OrganizeTemplateType;
import com.timevale.esign.sdk.tech.bean.seal.PersonTemplateType;
import com.timevale.esign.sdk.tech.bean.seal.SealColor;
import com.timevale.esign.sdk.tech.impl.constants.DeleteParamType;
import com.timevale.esign.sdk.tech.impl.constants.LicenseQueryType;
import com.timevale.esign.sdk.tech.impl.constants.SignType;
import com.timevale.esign.sdk.tech.service.EsignsdkService;
import com.timevale.esign.sdk.tech.service.factory.*;
import com.timevale.esign.sdk.tech.v3.service.factory.PdfDocumentServiceFactory;
import com.timevale.esign.sdk.tech.v3.service.factory.TemplateSealServiceFactory;
import com.timevale.tech.sdk.bean.HttpConnectionConfig;
import com.timevale.tech.sdk.bean.ProjectConfig;
import com.timevale.tech.sdk.bean.SignatureConfig;
import com.timevale.tech.sdk.constants.AlgorithmType;
import com.timevale.tech.sdk.constants.HttpType;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.Map;

/**
 * e签宝lib
 */

public class ESignLib {

    private Logger logger = Logger.getLogger(ESignLib.class);

    @Value("${esign.project.id}")
    private String ESIGN_PROJECT_ID;
    @Value("${esign.project.secret}")
    private String ESIGN_PROJECT_SECRET;
    @Value("${esign.api.url}")
    private String ESIGN_API_URL;

    /**
     * 初始化 e签宝
     *
     * @throws Exception
     */
    public void initProject() throws Exception {
        logger.info("【初始化e签宝方法执行开始】");

        String projectId = ESIGN_PROJECT_ID;
        String projectSecret = ESIGN_PROJECT_SECRET;
        String apiUrl = ESIGN_API_URL;
        ProjectConfig proCfg = new ProjectConfig();

        // 项目ID(应用ID)
        proCfg.setProjectId(projectId);// 1111563517
        // 项目Secret(应用Secret)
        proCfg.setProjectSecret(projectSecret); // 95439b0863c241c63a861b87d1e647b7
        // 开放平台地址
        proCfg.setItsmApiUrl(apiUrl);

        HttpConnectionConfig httpConCfg = new HttpConnectionConfig();
        // 协议类型，默认https
        httpConCfg.setHttpType(HttpType.HTTP);
        // 请求失败重试次数，默认5次
        httpConCfg.setRetry(5);
        // 代理服务IP地址
        // httpConCfg.setProxyIp(null);
        // 代理服务端口
        // httpConCfg.setProxyPort(0);

        SignatureConfig sCfg = new SignatureConfig();
        // 算法类型，默认HMAC-SHA256
        sCfg.setAlgorithm(AlgorithmType.HMACSHA256); // 可选RSA，但推荐使用HMACSHA256
        // e签宝公钥，可以从开放平台获取。若算法类型为RSA，此项必填
        sCfg.setEsignPublicKey("");
        // 平台私钥，可以从开放平台下载密钥生成工具生成。若算法类型为RSA，此项必填
        sCfg.setPrivateKey("");
        System.out.println("--项目初始化...");
        EsignsdkService sdk = EsignsdkServiceFactory.instance();
        Result result = sdk.init(proCfg, httpConCfg, sCfg);
        if (0 != result.getErrCode()) {

            logger.info("--项目初始化失败：errCode=" + result.getErrCode() + " msg=" + result.getMsg());
            throw new Exception("初始化e签宝方法执行异常");
        } else {
            System.out.println("--项目初始化成功！errCode=" + result.getErrCode() + " msg=" + result.getMsg());
        }

        logger.info("【初始化e签宝方法执行结束】");
    }

    public static AddAccountResult addAccount(PersonBean personBean) {
        return AccountServiceFactory.instance().addAccount(personBean);
    }

    /**
     * 创建个人模板印章
     *
     * @param accountId
     * @return
     */
    public static AddSealResult addTemplateSeal(String accountId) {
        return addTemplateSeal(accountId, PersonTemplateType.RECTANGLE, SealColor.RED);
    }

    /**
     * 创建个人模板印章
     *
     * @param accountId    账户id
     * @param templateType 模板类型
     * @param color        印章颜色
     * @return
     */
    private static AddSealResult addTemplateSeal(String accountId, PersonTemplateType templateType, SealColor color) {
        return SealServiceFactory.instance().addTemplateSeal(accountId, templateType, color);
    }

    /**
     * 用户盖章
     *
     * @param accountId
     * @param sealData
     * @param stream
     * @return
     */
    public static FileDigestSignResult localSignPDFCustomerSide(String accountId, String sealData,
                                                                SignPDFStreamBean stream) {
        PosBean posBean = new PosBean();
        posBean.setPosPage("1");
        posBean.setPosX(235.2F);
        posBean.setPosY(324.3F);

        // todo 位置信息待确定,读取配置文件
        return localSignPDFCustomerSide(accountId, sealData, stream, posBean, SignType.Single);
    }

    /**
     * 用户盖章
     *
     * @param accountId
     * @param sealData
     * @param stream
     * @param signPos
     * @param signType
     * @return
     */
    public static FileDigestSignResult localSignPDFCustomerSide(String accountId, String sealData,
                                                                SignPDFStreamBean stream, PosBean signPos, SignType signType) {
        return UserSignServiceFactory.instance().localSignPDF(accountId, sealData, stream, signPos, signType);
    }

    /**
     * 茉莉签单个章
     *
     * @param stream
     * @param sealData
     * @return
     */
    public static FileDigestSignResult localSignPDFMoliSideSingle(SignPDFStreamBean stream, String sealData) {
        PosBean posBean = new PosBean();
        posBean.setPosPage("1");
        posBean.setPosX(92.3F);
        posBean.setPosY(74.3F);
        // todo 位置信息待确定,读取配置文件
        return localSignPDFMoliSide(stream, posBean, sealData, SignType.Single);

    }

    /**
     * 茉莉签骑缝章
     *
     * @param stream
     * @param sealData
     * @return
     */
    public static FileDigestSignResult localSignPDFMoliSideEdges(SignPDFStreamBean stream, String sealData) {
        PosBean posBean = new PosBean();
        posBean.setPosPage("1-2");
        /*
         * posBean.setPosX(54.3F); posBean.setPosY(74.3F);
         */
        // todo 位置信息待确定,读取配置文件
        return localSignPDFMoliSide(stream, posBean, sealData, SignType.Edges);

    }

    /**
     * 茉莉盖章
     *
     * @param stream
     * @param posBean
     * @param sealData
     * @param signType
     * @return
     */
    public static FileDigestSignResult localSignPDFMoliSide(SignPDFStreamBean stream, PosBean posBean, String sealData,
                                                            SignType signType) {
        return SelfSignServiceFactory.instance().localSignPdf(stream, posBean, sealData, signType);
    }

    /**
     * pdf模版生成pdf文件 替换占位符
     *
     * @param stream
     * @param isFlat
     * @param txtFields
     * @return
     */
    public static FileCreateFromTemplateResult createFileFromTemplate(SignPDFStreamBean stream, boolean isFlat,
                                                                      Map<String, Object> txtFields) {
        return PdfDocumentServiceFactory.instance().createFileFromTemplate(stream, isFlat, txtFields);
    }

    /**
     * 根据证件号获取账户信息
     *
     * @param idNo
     * @param idNoType
     * @return
     */
    public static GetAccountProfileResult getAccountInfoByIdNo(String idNo, LicenseQueryType idNoType) {

        return AccountServiceFactory.instance().getAccountInfoByIdNo(idNo, idNoType);
    }

    /**
     * 更新个人账户信息
     *
     * @param accountId
     * @param person
     * @param deleteParamType
     * @return
     */
    public static Result updateAccount(String accountId, UpdatePersonBean person,
                                       List<DeleteParamType> deleteParamType) {
        return AccountServiceFactory.instance().updateAccount(accountId, person, deleteParamType);
    }

    /**
     * 本地创建公司印章
     *
     * @param type      模板类型
     * @param roundText 生成印章中的上弦文
     * @param hText     生成印章中的横向文内容
     * @param qText     生成印章中的下弦文内容
     * @param color     印章颜色
     * @return
     */
    private static AddSealResult createOfficialTemplateSeal(OrganizeTemplateType type, String roundText, String hText,
                                                            String qText, SealColor color) {
        return TemplateSealServiceFactory.instance().createOfficialTemplateSeal(type, roundText, hText, qText, color);
    }

    /**
     * 本地创建公司印章
     *
     * @param roundText 生成印章中的上弦文
     * @param hText     生成印章中的横向文内容
     * @param qText     生成印章中的下弦文内容
     * @return
     */
    public static AddSealResult createOfficialTemplateSeal(String roundText, String hText, String qText) {
        return createOfficialTemplateSeal(OrganizeTemplateType.STAR, roundText, hText, qText, SealColor.RED);
    }

}
